#pragma once

#include <iostream>
#include <pthread.h>
#include <functional>
#include "Sock.hpp"
#include "Protocol.hpp"

namespace tcpserver_ns
{
    using namespace Protocol_ns;
    using func_t = std::function<Response(const Request &)>;

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(int sock, std::string ip, uint16_t port, TcpServer *tsvrp)
            : _sock(sock), _ip(ip), _port(port), _tsvrp(tsvrp)
        {
        }
        ~ThreadData()
        {
        }

    public:
        int _sock;
        std::string _ip;
        uint16_t _port;
        TcpServer *_tsvrp;
    };

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port) : _func(func), _port(port)
        {
        }

        void InitServer()
        {
            // 初始化服务器
            _listensock.Socket();
            _listensock.Bind(_port);
            _listensock.Listen();
            logMessage(Info, "init server done, listensock: %d", _listensock.Fd());
        }

        void Start()
        {
            for (;;)
            {
                std::string clientip;
                uint16_t clientport;
                int sock = _listensock.Accept(&clientip, &clientport);
                if (sock < 0)
                {
                    continue;
                }
                logMessage(Debug, "get a new client, client info : [%s:%d]", clientip.c_str(), clientport);

                pthread_t tid;
                ThreadData *td = new ThreadData(sock, clientip, clientport, this);
                pthread_create(&tid, nullptr, ThreadRoutine, td);
            }
        }

        static void *ThreadRoutine(void *args)
        {
            pthread_detach(pthread_self());

            ThreadData *td = static_cast<ThreadData *>(args);
            td->_tsvrp->ServiceIO(td->_sock, td->_ip, td->_port);
            logMessage(Debug, "thread quit, client quit...");
            delete td;
            return nullptr;
        }

        void ServiceIO(int sock, const std::string &ip, const uint16_t &port)
        {
            std::string inbuffer;
            while (true)
            {
                //读取一个完整的请求报文
                std::string package;
                int n = ReadPackage(sock, inbuffer, &package);
                if (n == -1)
                {
                    break;
                }
                else if (n == 0)
                {
                    continue;
                }
                else
                {
                    //此时一定读取到了一个完整的请求报文，从中提取有效载荷
                    package = RemoveHeader(package, n);
                    //对请求报文进行反序列化
                    Request req;
                    req.Deserialize(package);
                    //根据请求报文进行业务处理，生成响应报文
                    Response resp = _func(req);
                    //对生成的响应报文进行序列化
                    std::string send_string;
                    resp.Serialize(&send_string);
                    //给响应报文添加报头
                    send_string = AddHeader(send_string);
                    //发送
                    send(sock, send_string.c_str(), send_string.size(), 0);
                }
            }
            close(sock);
        }

        ~TcpServer()
        {
            _listensock.Close();
        }

    private:
        uint16_t _port;
        Sock _listensock;
        func_t _func;
    };
}